package com.seari.gena.ciosServer.handler;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.gena.bean.ServerBean;
import com.seari.utils.PropertiesUtil;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import redis.clients.jedis.Jedis;

public class CIOSSender {
	
	protected static Logger logger = LoggerFactory.getLogger(CIOSSender.class);
	Channel channel;
	ServerBean bean;


	public CIOSSender(Channel channel, ServerBean bean) {

		this.channel = channel;
		this.bean = bean;
	}

	public void CiosSendData() {

		channel.eventLoop().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				Jedis jedis = null;
				try {
					logger.info("进入 CIOSSender");
					bean.setNt("nt: gena:update");
					String clientIP = bean.getCallback().split(":")[0];
					StringBuffer sb = new StringBuffer();
					String notify = new String();					
					jedis = JedisUtilProxy.getJedis();
					Properties prop = PropertiesUtil.loadConfig("genaLine8.properties");
					String FireAlarmLast = prop.getProperty("FireAlarmLast");
					String PowerSectionLast = prop.getProperty("PowerSectionLast");
					String VentilationLast = prop.getProperty("VentilationLast");
					if ("PowerSection".equals(bean.getSubscribe())) {
						//PowerSection
						String PowerStatus; //供电状态
						for(Map.Entry<String, String> entry:CIOSNotifyClientHandler.PowerSectionMap.entrySet()){
				            String redisValue = jedis.hmget("line_8", entry.getKey()).get(0);
							if (!entry.getValue().equals(redisValue)) {
								if ("1".equals(redisValue)) {
									PowerStatus = "Energized";// 供电
								} else  {
									PowerStatus = "Deenergized";// 断电
								}
								notify = "<?xml version=\"1.0\"?>"
										+ "<Envelope>"
										+ "<Body cls=\"PowerSection\" obj=\"" + prop.getProperty(entry.getKey()) + "\">"
										+ "<PowerStatus>" + PowerStatus + "</PowerStatus>"
										+ "</Body>"
										+ "</Envelope>";
								sb.append("NOTIFY / HTTP/1.1\r\n");
								sb.append("Host:" + clientIP + "\r\n");
								sb.append("Content-Length: " + notify.length() + "\r\n");
								sb.append(bean.getNt() + "\r\n");
								sb.append(bean.getSid() + "\r\n");
								sb.append("\r\n");
								sb.append(notify);
								logger.info("gena订阅发送的数据包：" + sb.toString());
								channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
								sb.delete(0, sb.length());
								CIOSNotifyClientHandler.PowerSectionMap.put(entry.getKey(), redisValue);
				            }
				         }
						
						 String redisValue = jedis.hmget("line_8", PowerSectionLast).get(0);
								if ("1".equals(redisValue)) {
									PowerStatus = "Energized";// 供电
								} else  {
									PowerStatus = "Deenergized";// 断电
								}
								notify = "<?xml version=\"1.0\"?>"
										+ "<Envelope>"
										+ "<Body cls=\"PowerSection\" obj=\"" + prop.getProperty(PowerSectionLast) + "\">"
										+ "<PowerStatus>" + PowerStatus + "</PowerStatus>"
										+ "</Body>"
										+ "</Envelope>";
								sb.append("NOTIFY / HTTP/1.1\r\n");
								sb.append("Host:" + clientIP + "\r\n");
								sb.append("Content-Length: " + notify.length() + "\r\n");
								sb.append(bean.getNt() + "\r\n");
								sb.append(bean.getSid() + "\r\n");
								sb.append("\r\n");
								sb.append(notify);
								logger.info("gena订阅发送的数据包：" + sb.toString());
								channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
								sb.delete(0, sb.length());
					} else if ("Ventilation".equals(bean.getSubscribe())) {
						// Ventilation						
						String FanStatus = "Fault";//风机状态
						String FanDirection = "";// 风向 
						String status0 = "";
						String status1 = "";
						String status2 = "";
						for (Map.Entry<String, String> entry : CIOSNotifyClientHandler.VentilationMap0.entrySet()) {
							status0 = jedis.hget("line_8", entry.getKey());
							status1 = jedis.hget("line_8", String.valueOf(Integer.parseInt(entry.getKey()) + 1));
							status2 = jedis.hget("line_8", String.valueOf(Integer.parseInt(entry.getKey()) + 2));
							if (!entry.getValue().equals(status0)
									|| !CIOSNotifyClientHandler.VentilationMap1
											.get(String.valueOf(Integer.parseInt(entry.getKey()) + 1)).equals(status1)
									|| !CIOSNotifyClientHandler.VentilationMap2
											.get(String.valueOf(Integer.parseInt(entry.getKey()) + 2))
											.equals(status2)) {
								if ("1".equals(status2) && "0".equals(status0) && "0".equals(status1)) {
									FanStatus = "Off";
									FanDirection = "";
								} else if ("0".equals(status2)) {
									if ("1".equals(status0) && "0".equals(status1)) {
										FanStatus = "On";
										FanDirection = "Uptrack";
									} else if ("0".equals(status0) && "1".equals(status1)) {
										FanStatus = "On";
										FanDirection = "Downtrack";
									} else {
										FanDirection = "";
									}
								}
								notify = "<?xml version=\"1.0\"?>"
										+ "<Envelope>"
										+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(entry.getKey()) + "\">"
										+ "<FanStatus>" + FanStatus + "</FanStatus>"
										+ "</Body>"
										+ "</Envelope>";				
								sb.append("NOTIFY / HTTP/1.1\r\n");
								sb.append("Host:" + clientIP + "\r\n");
								sb.append("Content-Length: " + notify.length() + "\r\n");
								sb.append(bean.getNt() + "\r\n");
								sb.append(bean.getSid() + "\r\n");
								sb.append("\r\n");
								sb.append(notify);
								logger.info("gena订阅发送的数据包：" + sb.toString());
								channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
								sb.delete(0, sb.length());
								
								notify = "<?xml version=\"1.0\"?>"
										+ "<Envelope>"
										+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(entry.getKey()) + "\">"
										+ "<FanDirection>" + FanDirection + "</FanDirection>"
										+ "</Body>"
										+ "</Envelope>";				
								sb.append("NOTIFY / HTTP/1.1\r\n");
								sb.append("Host:" + clientIP + "\r\n");
								sb.append("Content-Length: " + notify.length() + "\r\n");
								sb.append(bean.getNt() + "\r\n");
								sb.append(bean.getSid() + "\r\n");
								sb.append("\r\n");
								sb.append(notify);
								logger.info("gena订阅发送的数据包：" + sb.toString());
								channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
								sb.delete(0, sb.length());
								
								CIOSNotifyClientHandler.VentilationMap0.put(entry.getKey(), status0);
								CIOSNotifyClientHandler.VentilationMap1.put(String.valueOf(Integer.parseInt(entry.getKey()) + 1), status1);
								CIOSNotifyClientHandler.VentilationMap2.put(String.valueOf(Integer.parseInt(entry.getKey()) + 2), status2);								
							} 
						}
							status0 = jedis.hget("line_8", String.valueOf(Integer.parseInt(VentilationLast) - 2));
							status1 = jedis.hget("line_8", String.valueOf(Integer.parseInt(VentilationLast) - 1));
							status2 = jedis.hget("line_8", VentilationLast);
							if("1".equals(status2) && "0".equals(status0) && "0".equals(status1)){
								FanStatus = "Off";
							}else if("0".equals(status2)){
								if("1".equals(status0) && "0".equals(status1)){
									FanStatus = "On";
									FanDirection = "Uptrack";
								}else if("0".equals(status0) && "1".equals(status1)){
									FanStatus = "On";
									FanDirection = "Downtrack";
								}else{
									FanStatus = "Fault";
									FanDirection="";
								}
							}
							
							notify = "<?xml version=\"1.0\"?>"
									+ "<Envelope>"
									+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(String.valueOf(Integer.parseInt(VentilationLast) - 2)) + "\">"
									+ "<FanStatus>" + FanStatus + "</FanStatus>"
									+ "</Body>"
									+ "</Envelope>";				
							sb.append("NOTIFY / HTTP/1.1\r\n");
							sb.append("Host:" + clientIP + "\r\n");
							sb.append("Content-Length: " + notify.length() + "\r\n");
							sb.append(bean.getNt() + "\r\n");
							sb.append(bean.getSid() + "\r\n");
							sb.append("\r\n");
							sb.append(notify);
							logger.info("gena订阅发送的数据包：" + sb.toString());
							channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
							sb.delete(0, sb.length());
							
							notify = "<?xml version=\"1.0\"?>"
									+ "<Envelope>"
									+ "<Body cls=\"Ventilation\" obj=\"" + prop.getProperty(String.valueOf(Integer.parseInt(VentilationLast) - 2)) + "\">"
									+ "<FanDirection>" + FanDirection + "</FanDirection>"
									+ "</Body>"
									+ "</Envelope>";				
							sb.append("NOTIFY / HTTP/1.1\r\n");
							sb.append("Host:" + clientIP + "\r\n");
							sb.append("Content-Length: " + notify.length() + "\r\n");
							sb.append(bean.getNt() + "\r\n");
							sb.append(bean.getSid() + "\r\n");
							sb.append("\r\n");
							sb.append(notify);
							logger.info("gena订阅发送的数据包：" + sb.toString());
							channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
							sb.delete(0, sb.length());
							
						
					} else if ("FireAlarm".equals(bean.getSubscribe())) {
						//FireAlarm
						String AlarmStatus; //火警状态
						
						for(Map.Entry<String, String> entry:CIOSNotifyClientHandler.FireAlarmMap.entrySet()){
							String redisValue = jedis.hmget("line_8", entry.getKey()).get(0);
							if (!entry.getValue().equals(redisValue)) {
								if ("1".equals(redisValue)) {
									AlarmStatus = "On";// 
								} else  {
									AlarmStatus = "Off";// 
								}
								notify = "<?xml version=\"1.0\"?>"
										+ "<Envelope>"
										+ "<Body cls=\"FireAlarm\" obj=\"" + prop.getProperty(entry.getKey()) + "\">"
										+ "<AlarmStatus>" + AlarmStatus + "</AlarmStatus>"
										+ "</Body>"
										+ "</Envelope>";
								sb.append("NOTIFY / HTTP/1.1\r\n");
								sb.append("Host:" + clientIP + "\r\n");
								sb.append("Content-Length: " + notify.length() + "\r\n");
								sb.append(bean.getNt() + "\r\n");
								sb.append(bean.getSid() + "\r\n");
								sb.append("\r\n");
								sb.append(notify);
								logger.info("gena订阅发送的数据包：" + sb.toString());
								channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
								sb.delete(0, sb.length());
								CIOSNotifyClientHandler.FireAlarmMap.put(entry.getKey(), redisValue);
				            }
						}
						 String redisValue = jedis.hmget("line_8", FireAlarmLast).get(0);
							if ("1".equals(redisValue)) {
								AlarmStatus = "On";// 
							} else  {
								AlarmStatus = "Off";// 
							}
							notify = "<?xml version=\"1.0\"?>"
									+ "<Envelope>"
									+ "<Body cls=\"FireAlarm\" obj=\"" + prop.getProperty(FireAlarmLast) + "\">"
									+ "<AlarmStatus>" + AlarmStatus + "</AlarmStatus>"
									+ "</Body>"
									+ "</Envelope>";
							sb.append("NOTIFY / HTTP/1.1\r\n");
							sb.append("Host:" + clientIP + "\r\n");
							sb.append("Content-Length: " + notify.length() + "\r\n");
							sb.append(bean.getNt() + "\r\n");
							sb.append(bean.getSid() + "\r\n");
							sb.append("\r\n");
							sb.append(notify);
							logger.info("gena订阅发送的数据包：" + sb.toString());
							channel.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush
							sb.delete(0, sb.length());
						}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					JedisUtilProxy.close(jedis);
				}
			}
		}, 20, 2, TimeUnit.SECONDS);
	}

}
